import {
  defineComponent,
  ref,
} from 'vue'

import {
  ElButton,
  ElCol,
  ElMessage,
  ElMessageBox,
  ElRow,
} from 'element-plus'

import { createForm, onFormInit } from '@formily/core'

import { useRoute } from 'vue-router'

import { clone } from 'lodash-es'
import type { ComprehensiveScore } from '@/types/scholarship'
import { useDict } from '@/utils/dict'
import {
  editComprehensiveScore,
  getComprehensiveScoreListById,
} from '@/api/scholarship'
import ComprehensiveForm from '@/views/scholarship/comprehensiveScore/components/ComprehensiveForm'

export default defineComponent({
  setup() {
    const route = useRoute()
    const id = route.params.id as string
    const { sys_yes_no, ...dicts } = useDict('deyu', 'zhiyu', 'laoyu', 'shenyu', 'nengyu', 'sys_yes_no')
    const dictMap = [
      ['德育', 'deyu', 'deTotal'],
      ['智育', 'zhiyu', 'zhiTotal'],
      ['劳育', 'laoyu', 'laoTotal'],
      ['身育', 'shenyu', 'shenTotal'],
      ['能育', 'nengyu', 'nengTotal'],
    ] as const
    const originData = ref<ComprehensiveScore>()

    const form = createForm<ComprehensiveScore>({
      editable: false,
      effects() {
        onFormInit(async (form1) => {
          if (id) {
            const { data } = await getComprehensiveScoreListById(id)
            originData.value = clone(data)
            dictMap.forEach(([_, dictKey, fieldKey]) => {
              data[fieldKey] = dicts[dictKey].value
                .map(item => item.value)
                .filter((key) => {
                  const tmp = data[key as 'deHelp']
                  delete data[key as 'deHelp']
                  return tmp
                }) as unknown as string
            })
            form1.setValues(data, 'overwrite')
          }
        })
      },
    })

    const submit = async (state: string, reason?: string) => {
      if (originData.value) {
        await editComprehensiveScore({ ...originData.value, isPass: state, reason })
        ElMessage.success('操作成功')
        return
      }
      ElMessage.success('操作失败')
    }

    const reject = () => {
      ElMessageBox.prompt('', '拒绝原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async ({ value }) => {
        await submit(sys_yes_no.value[1].value, value)
      })
    }

    return () => (
      <div class="p-2 md:p-4 h-full">
        <ElRow gutter={10} class="mb-4">
          <ElCol span={1.5}>
            <ElButton
              type="primary"
              plain
              icon="Plus"
              onClick={() => submit(sys_yes_no.value[0].value, '')}
            >
              审核通过
            </ElButton>
          </ElCol>
          <ElCol span={1.5}>
            <ElButton
              type="danger"
              plain
              icon="Plus"
              onClick={reject}
            >
              审核拒绝
            </ElButton>
          </ElCol>
        </ElRow>
        <ComprehensiveForm form={form} />
      </div>
    )
  },
})
